﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：MallWebApiControllerBase.cs
// 功能描述：TongTongMall.MallWeb
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using TongTongMall.MallWeb.Application.Configuration;
using TongTongMall.MallWeb.Application.Configuration.Session;
using TongTongMall.MallWeb.Core.Enums;
using TongTongMall.MallWeb.Core.Instance;
using TongTongMall.MallWeb.WebApi.Filter;
using TongTongMall.Runtime.Session;
using TongTongMall.UI;
using TongTongMall.WebApi.WebApi.Controllers;

namespace TongTongMall.MallWeb.WebApi.Controllers
{
    [ApiAuthorization]
    public class MallWebApiControllerBase : TongTongMallBaseController
    {

        public IApplicationInstance Instance { get; set; } = ApplicationDefaultInstance.Instance;

        public new IMallWebSession Session { get; set; }= NullMallWebSession.Instance;



        /// <summary>
        /// 验证是否登录
        /// </summary>
        public bool IsLogin { get { return Session.UserID.HasValue; } }

        /// <summary>
        /// 检查错误 
        /// 只检查post参数内容
        /// </summary>
        protected virtual void CheckModelState()
        {
            if (!ModelState.IsValid)
            {
                throw new UserFriendlyException((int)ErrCode.ParamErr, GetModelErrors());
            }
        }

        protected string GetModelErrors()
        {
            List<string> sb = new List<string>();
            //获取所有错误的Key
            List<string> Keys = ModelState.Keys.ToList();
            //获取每一个key对应的ModelStateDictionary
            foreach (var key in Keys)
            {
                var errors = ModelState[key].Errors.ToList();
                //将错误描述添加到sb中
                foreach (var error in errors)
                {
                    var message = string.IsNullOrEmpty(error.ErrorMessage) ? error.Exception.Message : error.ErrorMessage;
                    sb.Add(message);
                }
            }
            return String.Join("；", sb);
        }

    }
}
